package com.raph.server;

import com.raph.db.DbUtils;
import com.raph.message.Message;
import com.raph.message.MessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Server {
    private static ServerSocket server = null;
    private static final Logger logger = LoggerFactory.getLogger(Server.class);
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(10);
    private static boolean flag = true;


    public Server() {
        DbUtils.init();
        try {
            server = new ServerSocket(9001);
            logger.info("==========服务器已启动==========");
            while(flag) {
                Socket socket = server.accept();
                logger.info("新连接已建立");
                threadPool.execute(new ClientHandler(socket));
            }
        } catch (IOException e) {
            if(flag) {
                logger.error("服务器启动失败！");
            }
            else {
                logger.info("服务器已关闭");
            }
        }
    }

    public static void shutDown() {
        flag = false;
        try{
            if(server != null && !server.isClosed()){
                server.close();
            }
        } catch (IOException e) {
            logger.warn("服务器关闭异常: {}", e.getMessage(), e);
        }
    }
}
